import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Modal, Pagination, Popconfirm, Button, Row, Col } from 'antd';
import styles from './../Users.css';
import moment from 'moment';
import Factory from '../../factory';
import * as datetime from '../../../utils/datetime'
import dataEditCreate from '../../addons/DataEdit'
import dataTableCreate from '../../addons/DataTable'
import DataEditTable from '../../addons/DataEditTable'
import CompClieKhglCuidForm from './CompClieKhglCuidForm'
import * as accountService from '../../../services/AccountDivi';
const daoName = "VCompClieKhgl";
const ButtonGroup = Button.Group;
const columns = [
    { title: '客户名称', width: 215, sorter: true, dataIndex: 'CUNM', key: 'CUNM', dispaly: true, filter: true },
    { title: '组织机构代码', width: 140, sorter: true, dataIndex: 'ENCD', key: 'ENCD', dispaly: true, filter: true },
];
const controls = [
    { name: 'CUNM', required: true, type: 'text', label: '客户名称',  grid: 12 / 24 },
    { name: 'ENCD', required: true, type: 'text', label: '组织机构代码', min: 1, max: 50, grid: 12 / 24 },
];
const columnsUphmDivi = [
    { title: '客户名称', width: 215, sorter: true, dataIndex: 'CUNM', key: 'CUNM', dispaly: true, filter: true },
    { title: '组织机构代码', width: 140, sorter: true, dataIndex: 'ENCD', key: 'ENCD', dispaly: true, filter: true },
];
const controlsUphm = [
    { name: 'CUNM', required: true, type: 'text', label: '客户名称',  grid: 12 / 24 },
    { name: 'ENCD', required: true, type: 'text', label: '组织机构代码', min: 1, max: 50, grid: 12 / 24 },
];
const EditFrom = dataEditCreate(daoName);
const DataTable = dataTableCreate(daoName);
class CompClieKhglForm extends Component {
    constructor(props) {
        super(props);
        this.state = {

            dataChange: false,
            diviList: [],
            zhmData: {},
            glhmData: {},
            glhmDataSource: [],
            diviDisplay: {
                div2: 'block',
                div3: 'none',
                lable1: '添加关联客户',
                isTj: true,
            },
            otherkey:-1
        };
    }
    componentWillReceiveProps(nextProps) {
        const k = nextProps.otherSelectedRowKeys.length
        if (k > 0) {
          this.state.otherkey = nextProps.otherSelectedRowKeys[k - 1]
        }
    };
    onSelectChangeHandler(newList, delKeys) {
      let diviList = this.state.diviList
      newList.map(data => {
        diviList.push(data)
      })
      delKeys.map(key => {
        const index = diviList.findIndex(divi => divi["CUID"] === key)
        diviList.splice(index, 1)
      })
      this.setState({ diviList })
    }
    componentDidMount() {
        this.props.dispatch({
            type: `${daoName}/setKeyName`,
            payload: { keyName: "CUID", permID: this.props.permID }
        });
        this.props.dispatch({
            type: `${daoName}/fetch`,
            payload: { daoName, page: 1, pageSize: 10 }
        });
        this.loadOptionData();
    }
    loadOptionData() {
        let options = []
        controls.map(c => {
            if (c.fetch) {
                let f = c.fetch;
                if (c.type === 'cascader-select') {
                    f.isCascader = true;
                }
                if (c.type !== 'search') {
                    options.push(f);
                }
            }
        })
        if (daoName && options.length > 0) {
            this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
        }
    }
    showDiviHandler() {
        let diviDisplay = {}
        if (this.state.diviDisplay.isTj) {
            diviDisplay = {
                div3:'',
                div2:'none',
                lable1:'返回',
                isTj:false,
            }
        } else {
            diviDisplay = {
                div3:'none',
                div2:'',
                lable1:'添加关联客户',
                isTj:true,
            }
        }
        let diviList = [];
        this.setState({diviDisplay,diviList})
        this.props.dispatch({
            type: `${daoName}/setSelectedRowKeys`,
            payload: { selectedRowKeys: [] }
        });
    }
    addSeachXghmHandler() {
        if (this.state.diviList.length === 0) {
            message.error('关联客户失败！请选择一个主客户！');
            return;
        }
        let data = {
            CUID: this.state.glhmData.ID,
            CUNM: this.state.glhmData.CUNM,
            ENCD: this.state.glhmData.ENCD
        }
        let dataSource = this.refs.diviUphmTable.state.datas;
        //验证：添加的员工是否重复
        for (let i = 0; i < dataSource.length; i++) {
            if (Number(dataSource[i]["CUID"]) === Number(data["CUID"])) {
                message.error('关联客户失败！所选客户已关联，请重新选择客户关联！');
                return;
            }
        }
        dataSource.push(data);
        this.setState({ glhmDataSource: dataSource })
    }
    deleteSeachXghmHandler() {
        const keys = this.refs.diviUphmTable.getSelectedRowKeys();
        let datas = this.refs.diviUphmTable.state.datas;
        let total = this.refs.diviUphmTable.state.total;
        let indexs = []
        const keyName = "CUID"
        datas.map((d, k) => {
            for (let i = 0; i < keys.length; i++) {
                if (d[keyName] === keys[i]) {
                    indexs.push(k)
                    total--
                }
            }
        })
        let delDatas = this.refs.diviUphmTable.state.delDatas
        for (let j = indexs.length - 1; j >= 0; j--) {
            const k = indexs[j]
            if (datas[k].$state !== 1) {
                delDatas.push(datas[k])
            }
            datas.splice(k, 1)
        }
        this.setState({ glhmDataSource: datas })
    }
    submitSeachXghmHandler() {
        const datas = this.refs.diviUphmTable.state.datas;
        const witDividatas = this.state.diviList;
        if (witDividatas.length <= 0) {
            message.info('请选择要关联客户的主客户!');
            return;
        }
        let CUID = 0;
        CUID = Number(witDividatas[0].CUID);
        let dataSource = []
        datas.map(d => {
            let data = {
                CUID: CUID,
                LCUID: Number(d.CUID)
            }
            dataSource.push(data);
        })
        accountService.CompClieKhglInsGl({ CUID,dataSource }
        ).then(function (data) {
            if (data !== "OK") {
                message.info('添加关联客户失败！');
                return;
            } else if (data === "OK"){
                message.info('关联客户添加成功！');
                this.props.dispatch({
                    type: `${daoName}/fetch`,
                    payload: { daoName }
                });
            }
        }.bind(this));
        let diviDisplay = {
            div3:'none',
            div2:'',
            lable1:'添加关联客户',
            isTj:true,
        }
        let glhmDataSource = [];
        let diviList = [];
        this.setState({diviDisplay,glhmDataSource,diviList})
        this.props.dispatch({
            type: `${daoName}/setSelectedRowKeys`,
            payload: { selectedRowKeys: [] }
        });
    }
    showTableHandler() {
        if (this.state.zhmData.ID===undefined) {
            message.error('主客户不能为空，请选择主客户!');
            return;
        }
        let CUID= this.state.zhmData.ID;
        accountService.CompClieKhglInsC({ CUID }
        ).then(function (data) {
            if (data !== "OK") {
                message.error('主客户已存在，无需再次添加！');
                return;
            } else if (data === "OK"){
                message.success('主客户添加成功！');
                this.props.dispatch({
                    type: `${daoName}/fetch`,
                    payload: { daoName }
                });
            }
        }.bind(this));
        this.props.dispatch({
            type: `${daoName}/setSelectedRowKeys`,
            payload: { selectedRowKeys: [] }
        });
    }
    //删除主客户
    delMainClie(){
        const keys = this.props.selectedRowKeys;
        if (keys.length <= 0) {
            message.error('请选择要删除的主客户信息!');
            return;
        }
        let ids = keys[0]
        Modal.confirm({
            title: '提示',
            content: `你确认要删除主客户吗？`,
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                accountService.DelCompMainClie({ ids }
                ).then(function (data) {
                    if (data === 'OK') {
                        message.success('删除主客户成功')
                        this.props.dispatch({
                            type: `${daoName}/fetch`,
                            payload: { daoName }
                        });
                    } else if(data === 'no'){
                        message.error("主客户下有关联的客户信息，删除失败")
                        return;
                    }else{
                        message.error('删除失败！' + data)
                        return;
                    }
                }.bind(this)).catch(function (ex) {
                    console.log('请求出错', ex)
                });
                this.props.dispatch({
                    type: `${daoName}/setSelectedRowKeys`,
                    payload: { selectedRowKeys: [] }
                });
            }
        });
    }
    //删除关联客户
    DelCompOtherClie(){
        const okeys = this.state.otherkey
        const keys = this.props.selectedRowKeys
        let mkeys = keys[0]
        if (okeys===-1){
            message.error("请选择要删除的关联客户数据行！")
            return;
        }
        Modal.confirm({
            title: '提示',
            content: `你确认要删除该关联客户吗？`,
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                accountService.DelCompOtherClie({ mkeys,okeys }
                ).then(function (data) {
                    if (data === 'OK') {
                        message.success('删除关联客户成功')
                    } else{
                        message.error('删除关联客户失败！' + data)
                        return;
                    }
                }.bind(this)).catch(function (ex) {
                    console.log('请求出错', ex)
                });
                this.props.dispatch({
                    type: `${daoName}/setSelectedRowKeys`,
                    payload: { selectedRowKeys: [] }
                });
            }
        });
        
    }
    seachHandler(data) {
        this.state.zhmData = data;
    }
    seachXgHandler(data) {
        this.state.glhmData = data;
    }
    render() {
        let { showEdit, record, offsetHeight, permID, popedomTypes } = this.props
        let height = (offsetHeight - 128) * 0.50 - 41
        let data = [{ value: '1', label: '添加主客户', onClick: this.showTableHandler.bind(this) },{ value: '2', label: '删除主客户', onClick: this.delMainClie.bind(this) }]
        let pTypes = popedomTypes[permID]
        if (pTypes.indexOf("2") !== -1) {
            data.push({ value: '3', label: this.state.diviDisplay.lable1, onClick: this.showDiviHandler.bind(this) })
            data.push({ value: '4', label: '删除关联客户', onClick: this.DelCompOtherClie.bind(this) })
        }
        const controlsCx = [
            { name: 'CUID', required: true, type: 'search', label: '主客户', grid: 9 / 24, layout: { labelSpan: 5, wrapperSpan: 15 }, fetch: { daoName: 'CompClie', searchColumns: ['ENCD', 'CUNM'], optionTpl: 'CUNM', valueTpl: "ID", onSelect: this.seachHandler.bind(this) }, dataType: "number",placeholder: '请输入客户名称...' , seekType: 2 },
            { name: 'button', required: false, type: 'button-group', grid: 15 / 24, data: data, layout: { labelSpan: 0, wrapperSpan: 20 } },
        ]
        const controlsUphm = [
            { name: 'LCUID', required: true, type: 'search', label: '关联客户', grid: 9 / 24, layout: { labelSpan: 5, wrapperSpan: 15 }, fetch: { daoName: 'CompClie', searchColumns: ['ENCD', 'CUNM'], optionTpl: 'CUNM', valueTpl: "ID", onSelect: this.seachXgHandler.bind(this) }, dataType: "number", placeholder: '请输入客户名称...' ,seekType: 2 },
            { name: 'button', required: false, type: 'button-group', grid: 15 / 24, data: [{ value: '1', label: '添加', onClick: this.addSeachXghmHandler.bind(this) }, { value: '2', label: '删除', onClick: this.deleteSeachXghmHandler.bind(this) }, { value: '3', label: '提交', onClick: this.submitSeachXghmHandler.bind(this) }] , layout: { labelSpan: 0, wrapperSpan: 20 }},
        ]
        return (
            <div className={styles.normal} style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
                <div>
                    <div className={styles.create} style={{ paddingBottom: '-16px' }}>
                        <EditFrom ref="CompClieKhglForm" daoName={daoName} controls={controlsCx} record={record} clearItemMargin={true} />
                    </div>
                    <font style={{fontSize:"20px",fontWeight:"bold"}}>【主客户信息】</font>
                    <DataTable ref="userTable" daoName={daoName} columns={columns} controls={controls}  onSelectChange={this.onSelectChangeHandler.bind(this)} height={height} permID={permID} />
                    <div style={{ display: this.state.diviDisplay.div2 }} id="showCompDiviDiv" >
                        <font style={{fontSize:"20px",fontWeight:"bold"}}>【关联客户信息】</font>
                        <CompClieKhglCuidForm permID={permID} />
                    </div>
                    <div style={{ display: this.state.diviDisplay.div3 }} id="UpCompfkhm">
                        <DataEditTable columns={columnsUphmDivi} dataSource={this.state.glhmDataSource} ref="diviUphmTable"
                            height={150} keyName={"CUID"} footer={false} multiSelect={true} />
                        <EditFrom ref="CompClieKhglCuidForm" daoName={daoName} controls={controlsUphm} record={record} clearItemMargin={true} />
                    </div>
                </div>
            </div>
        )
    }
}

function mapStateToProps(state) {
    const { showEdit, record, selectedRowKeys, list, keyName } = state[daoName];
    const { offsetHeight, userID, orgID, pOrgID, popedomTypes } = state.menus
    const otherSelectedRowKeys = state['VCompClieKhglGl'].selectedRowKeys;
    return {
        userID,
        orgID,
        pOrgID,
        popedomTypes,
        showEdit,
        selectedRowKeys,
        list,
        keyName,
        offsetHeight,
        record,
        otherSelectedRowKeys
    }
}
CompClieKhglForm = connect(mapStateToProps)(CompClieKhglForm)
export default CompClieKhglForm;

let render = (props) => React.createElement(CompClieKhglForm, props);
let f = new Factory()
f.set("CompClieKhglForm", render)
